package python;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 定时执行python脚本
 *
 * @author: zhangwei
 */
//@Configuration
@Slf4j
public class PythonScript {

    /**
     * 每天1点执行一次 爬取农作物价格数据
     */
    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(fixedDelay = 240 * 60 * 1000L)
    public void graspMainPrice() {
        executePythonScript("python/main_price.py");
    }

    /**
     * 每天2点执行一次 爬取新闻信息
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void graspMainNews() {
        executePythonScript("python/main_news.py");
    }

    /**
     * 执行python脚本
     *
     * @param path python脚本路径
     */
    public void executePythonScript(String path) {
        URL pythonUrl = this.getClass().getClassLoader().getResource(path);
        if (Objects.isNull(pythonUrl)) {
            return;
        }
        String filePath = pythonUrl.getPath();
        if (System.getProperty("os.name").toLowerCase().contains("win") && filePath.startsWith("/")) {
            filePath = filePath.substring(1);
        }
        ProcessBuilder processBuilder = new ProcessBuilder("python", filePath);
        try {
            Process process = processBuilder.start();
            // 读取Python脚本的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                log.info("python脚本执行输出信息：{}", line);
            }

            // 等待Python脚本执行完成
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                log.info("python脚本成功: {}", exitCode);
            }
        } catch (IOException | InterruptedException e) {
            log.error("python脚本执行异常：{}", e.getMessage(), e);
        }
    }

}
